package com.situ.mall.service.impl;

import java.util.List;

import javax.jws.WebParam.Mode;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.dao.CartMapper;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.User;
import com.situ.mall.service.ICartService;

@Service
public class CartServiceImpl implements ICartService{
	@Autowired
	private CartMapper cartMapper;

	@Override
	public ServerResponse insert(Integer productId, Integer num, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Cart cart = new Cart();
		cart.setUserId(user.getId());
		cart.setProductId(productId);
		cart.setQuantity(num);
		cart.setChecked(1);
		
		//判断这件商品是否在这个用户的购物车中
		int cartCount = cartMapper.selectCountByUserIdAndProductId(user.getId(), productId);
		int count = 0;
		//1、如果在这个用户的购物车中，只需要更新一下数量
		if (cartCount > 0) {
			count = cartMapper.updateQuantityByUserIdAndProductId(num, user.getId(), productId, 1);
		} else {
			//2、如果不在这个用户购物车中，直接插入这条购物车信息
			count = cartMapper.insert(cart);
		}
		if (count == 1) {
			return ServerResponse.createSuccess("加入购物车成功");
		} 
		return ServerResponse.createSuccess("加入购物车失败");
	}
	
	@Override
	public List<Cart> selectByUserId(Integer id) {
		return cartMapper.selectByUserId(id);
	}

	@Override
	public ServerResponse deleteById(Integer cartId) {
		int count = cartMapper.deleteByPrimaryKey(cartId);
		if (count == 1) {
			return ServerResponse.createSuccess("删除成功");
		}
		
		return ServerResponse.createError("删除失败");
	}

	@Override
	public ServerResponse updateQuantityByUserIdAndProductId(Integer productId, Integer num, HttpSession session) {
		User user = (User) session.getAttribute("user");
		int count = cartMapper.updateQuantityByUserIdAndProductId(num, user.getId(), productId, null);;
		if (count == 1) {
			return ServerResponse.createSuccess("更新成功");
		} 
		return ServerResponse.createSuccess("更新失败");
	}

	@Override
	public ServerResponse updateCheckStatusByUserIdAndProductId(Integer productId, Integer checked,
			HttpSession session) {
		User user = (User) session.getAttribute("user");
		int count = cartMapper.updateCheckStatusByUserIdAndProductId(checked, user.getId(), productId);;
		if (count == 1) {
			return ServerResponse.createSuccess("更新成功");
		} 
		return ServerResponse.createSuccess("更新失败");
	}

}
